package cpu.footprint.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cpu.footprint.R;
import cpu.footprint.adapter.CityAdapter;
import cpu.footprint.bean.CityItem;
import cpu.footprint.common.BaseActivity;
import cpu.footprint.util.CityData;
import cpu.footprint.util.ViewUtil;
import cpu.footprint.widget.ContactItemInterface;
import cpu.footprint.widget.ContactListViewImpl;

/**
 * Created by Administrator on 2017/3/18.
 */
@ContentView(R.layout.activity_citylist)
public class CityListActivity extends BaseActivity implements TextWatcher{
    @ViewInject(R.id.title_content)
    private TextView title_content;//title内容
    @ViewInject(R.id.title_menu_text)
    private TextView title_menu_text;//title功能
    @ViewInject(R.id.title_menu_image)
    private ImageView title_menu_image;//title功能
    private Context context_ = CityListActivity.this;
    @ViewInject(R.id.listview)
    private ContactListViewImpl listview;
    @ViewInject(R.id.input_search_query)
    private EditText searchBox;
    private String searchString;
    private Object searchLock = new Object();
    boolean inSearchMode = false;
    private final static String TAG = "MainActivity2";
    private List<ContactItemInterface> contactList;
    private List<ContactItemInterface> filterList;
    private SearchListTask curSearchTask = null;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        if(title_content!=null) {
            title_content.setText("选择城市");
            title_menu_image.setVisibility(View.GONE);
            title_menu_text.setVisibility(View.GONE);
        }
        filterList = new ArrayList<ContactItemInterface>();
        contactList = CityData.getSampleContactList();
        CityAdapter adapter = new CityAdapter(this, R.layout.city_item, contactList);
        listview.setFastScrollEnabled(true);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView parent, View v, int position,
                                    long id){
                List<ContactItemInterface> searchList = inSearchMode ? filterList
                        : contactList;
                Intent intent=new Intent();
                intent.putExtra("city",searchList.get(position).getDisplayInfo());
                setResult(1,intent);
                overridePendingTransition(0,R.anim.fade);
                CityListActivity.this.finish();
            }
        });
        searchBox = (EditText) findViewById(R.id.input_search_query);
        searchBox.addTextChangedListener(this);
        TextView textView= (TextView) findViewById(R.id.text_allCity);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                allCity(v);
            }
        });
    }
    public void allCity(View v){
        Intent intent=new Intent();
        intent.putExtra("city","全部");
        setResult(1,intent);
        overridePendingTransition(0,R.anim.fade);
        CityListActivity.this.finish();
    }
    @Override
    public void afterTextChanged(Editable s){
        searchString = searchBox.getText().toString().trim().toUpperCase();
        if (curSearchTask != null
                && curSearchTask.getStatus() != AsyncTask.Status.FINISHED){
            try
            {
                curSearchTask.cancel(true);
            } catch (Exception e)
            {
                Log.i(TAG, "Fail to cancel running search task");
            }
        }
        curSearchTask = new SearchListTask();
        curSearchTask.execute(searchString);
    }

    @Event(value={R.id.title_back})
    private void  onClick(View v) {
        switch (v.getId()){
            case R.id.title_back:{
                this.finish();
                overridePendingTransition(0,R.anim.fade);
            }break;
        }
    }

    /**
     * 重写后退函数
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            CityListActivity.this.finish();
            overridePendingTransition(0,R.anim.fade);
            return true;
        } else
            return super.onKeyDown(keyCode, event);
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after){  }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
        // do nothing
    }

    private class SearchListTask extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            filterList.clear();
            String keyword = params[0];
            inSearchMode = (keyword.length() > 0);
            if (inSearchMode)
            {
                // get all the items matching this
                for (ContactItemInterface item : contactList)
                {
                    CityItem contact = (CityItem) item;

                    boolean isPinyin = contact.getFullName().toUpperCase().indexOf(keyword) > -1;
                    boolean isChinese = contact.getNickName().indexOf(keyword) > -1;

                    if (isPinyin || isChinese)
                    {
                        filterList.add(item);
                    }

                }

            }
            return null;
        }

        protected void onPostExecute(String result)
        {

            synchronized (searchLock)
            {

                if (inSearchMode)
                {

                    CityAdapter adapter = new CityAdapter(context_,R.layout.city_item, filterList);
                    adapter.setInSearchMode(true);
                    listview.setInSearchMode(true);
                    listview.setAdapter(adapter);
                } else
                {
                    CityAdapter adapter = new CityAdapter(context_,R.layout.city_item, contactList);
                    adapter.setInSearchMode(false);
                    listview.setInSearchMode(false);
                    listview.setAdapter(adapter);
                }
            }

        }
    }

}
